import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Card, 
  Button, 
  Space, 
  Tag, 
  Modal, 
  Form, 
  Input, 
  Select, 
  message,
  Descriptions,
  InputNumber,
  DatePicker,
  Popconfirm
} from 'antd';
import { 
  BankOutlined, 
  EyeOutlined,
  CheckOutlined,
  CloseOutlined,
  EditOutlined,
  DeleteOutlined,
  PlusOutlined
} from '@ant-design/icons';
import axios from 'axios';
import dayjs from 'dayjs';

const { Option } = Select;
const { TextArea } = Input;
const { RangePicker } = DatePicker;

const JobManagement = () => {
  const [loading, setLoading] = useState(false);
  const [jobs, setJobs] = useState([]);
  const [selectedJob, setSelectedJob] = useState(null);
  const [detailModalVisible, setDetailModalVisible] = useState(false);
  const [auditModalVisible, setAuditModalVisible] = useState(false);
  const [addModalVisible, setAddModalVisible] = useState(false);
  const [workerDetailModalVisible, setWorkerDetailModalVisible] = useState(false);
  const [selectedWorker, setSelectedWorker] = useState(null);
  const [employers, setEmployers] = useState([]);
  const [workers, setWorkers] = useState([]);
  const [form] = Form.useForm();
  const [addForm] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [filters, setFilters] = useState({
    status: '',
    jobType: ''
  });

  useEffect(() => {
    fetchJobs();
    fetchEmployers();
    fetchWorkers();
  }, [pagination.current, pagination.pageSize, filters]);

  const fetchJobs = async () => {
    try {
      setLoading(true);
      const token = localStorage.getItem('admin_token');
      console.log('正在获取岗位列表，token:', token ? '已设置' : '未设置');
      
      const response = await axios.get('/api/admin/jobs', {
        headers: { Authorization: `Bearer ${token}` },
        params: {
          page: pagination.current - 1,
          size: pagination.pageSize,
          status: filters.status || ''
        }
      });

      console.log('岗位列表API响应:', response.data);

      // 兼容多种响应格式
      if (response.data.success || response.data.code === 200) {
        const jobData = response.data.data || response.data;
        const jobList = jobData.content || jobData || [];
        const totalCount = jobData.totalElements || jobData.total || jobList.length;
        
        console.log('解析的岗位数据:', jobList);
        console.log('总数:', totalCount);
        
        setJobs(jobList);
        setPagination(prev => ({
          ...prev,
          total: totalCount
        }));
      } else {
        console.error('API返回失败:', response.data);
        message.error(response.data.message || '获取岗位列表失败');
        setJobs([]);
      }
    } catch (error) {
      console.error('获取岗位列表失败:', error);
      
      // 如果是401错误，提示重新登录
      if (error.response && error.response.status === 401) {
        message.error('登录已过期，请重新登录');
        localStorage.removeItem('admin_token');
        return;
      }
      
      // 其他错误情况下显示空列表，不使用模拟数据
      message.error('获取岗位列表失败，请检查网络连接');
      setJobs([]);
      setPagination(prev => ({ ...prev, total: 0 }));
    } finally {
      setLoading(false);
    }
  };

  // 获取用工方列表
  const fetchEmployers = async () => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.get('/api/admin/employers', {
        headers: { Authorization: `Bearer ${token}` },
        params: { page: 0, size: 1000 } // 获取所有用工方
      });

      if (response.data.code === 200) {
        const employerData = response.data.data;
        const employerList = employerData.content || employerData || [];
        setEmployers(employerList);
      }
    } catch (error) {
      console.error('获取用工方列表失败:', error);
    }
  };

  // 获取劳动者列表
  const fetchWorkers = async () => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.get('/api/admin/workers', {
        headers: { Authorization: `Bearer ${token}` },
        params: { page: 0, size: 1000 } // 获取所有劳动者
      });

      if (response.data.code === 200) {
        const workerData = response.data.data;
        const workerList = workerData.content || workerData || [];
        setWorkers(workerList);
      }
    } catch (error) {
      console.error('获取劳动者列表失败:', error);
    }
  };

  const handleAudit = async (values) => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.put(`/api/admin/jobs/${selectedJob.id}/audit`, 
        {
          status: values.status,
          auditRemark: values.auditRemark
        },
        { headers: { Authorization: `Bearer ${token}` } }
      );

      if (response.data.success || response.data.code === 200) {
        message.success('审核完成');
        setAuditModalVisible(false);
        form.resetFields();
        // 重置分页并刷新列表
        setPagination(prev => ({ ...prev, current: 1 }));
        await fetchJobs(); // 等待刷新完成
      } else {
        message.error(response.data.message || '审核失败');
      }
    } catch (error) {
      console.error('审核失败:', error);
      // 优化错误处理，显示具体的错误信息
      if (error.response && error.response.data) {
        const errorMessage = error.response.data.message || error.response.data.error || '审核失败';
        message.error(errorMessage);
      } else if (error.message) {
        message.error(error.message);
      } else {
        message.error('审核失败，请检查网络连接');
      }
    }
  };

  const handleAddJob = async (values) => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.post('/api/admin/jobs', values, {
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.success || response.data.code === 200) {
        message.success('岗位创建成功');
        setAddModalVisible(false);
        addForm.resetFields();
        // 重置分页并刷新列表
        setPagination(prev => ({ ...prev, current: 1 }));
        await fetchJobs(); // 等待刷新完成
      } else {
        message.error(response.data.message || '岗位创建失败');
      }
    } catch (error) {
      console.error('岗位创建失败:', error);
      // 优化错误处理，显示具体的错误信息
      if (error.response && error.response.data) {
        const errorMessage = error.response.data.message || error.response.data.error || '岗位创建失败';
        message.error(errorMessage);
      } else if (error.message) {
        message.error(error.message);
      } else {
        message.error('岗位创建失败，请检查网络连接');
      }
    }
  };

  const handleDelete = async (jobId) => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.delete(`/api/admin/jobs/${jobId}`, {
        headers: { Authorization: `Bearer ${token}` }
      });

      if (response.data.code === 200) {
        message.success('岗位删除成功');
        fetchJobs();
      } else {
        message.error(response.data.message || '岗位删除失败');
      }
    } catch (error) {
      console.error('删除岗位失败:', error);
      if (error.response && error.response.data) {
        message.error(error.response.data.message || '岗位删除失败');
      } else {
        message.error('岗位删除失败，请检查网络连接');
      }
    }
  };

  const showJobDetail = (job) => {
    setSelectedJob(job);
    setDetailModalVisible(true);
  };

  const showAuditModal = (job) => {
    setSelectedJob(job);
    form.setFieldsValue({
      status: 'PUBLISHED',
      auditRemark: ''
    });
    setAuditModalVisible(true);
  };

  const getJobTypeText = (type) => {
    const typeMap = {
      'FULL_TIME': '全职',
      'PART_TIME': '兼职',
      'TEMPORARY': '临时工',
      'INTERNSHIP': '实习'
    };
    return typeMap[type] || type;
  };

  const getSalaryTypeText = (type) => {
    const typeMap = {
      'HOURLY': '时薪',
      'DAILY': '日薪',
      'MONTHLY': '月薪'
    };
    return typeMap[type] || type;
  };

  const getStatusColor = (status) => {
    const colorMap = {
      'DRAFT': 'gray',
      'PUBLISHED': 'blue',
      'ACTIVE': 'green',
      'WAITING_FOR_WORKER': 'orange',
      'WORKER_ASSIGNED': 'cyan',
      'PAUSED': 'yellow',
      'CLOSED': 'gray',
      'COMPLETED': 'green',
      'CANCELLED': 'red'
    };
    return colorMap[status] || 'default';
  };

  const getStatusText = (status) => {
    const statusMap = {
      'DRAFT': '草稿',
      'PUBLISHED': '已发布',
      'ACTIVE': '活跃',
      'WAITING_FOR_WORKER': '等待用工中',
      'WORKER_ASSIGNED': '已获取用工',
      'PAUSED': '暂停',
      'CLOSED': '关闭',
      'COMPLETED': '已完成',
      'CANCELLED': '取消'
    };
    return statusMap[status] || status;
  };

  // 显示劳动者详情
  const showWorkerDetail = async (workerId) => {
    try {
      const token = localStorage.getItem('admin_token');
      const response = await axios.get(`/api/admin/workers/${workerId}`, {
        headers: { Authorization: `Bearer ${token}` }
      });
      
      if (response.data.code === 200) {
        setSelectedWorker(response.data.data);
        setWorkerDetailModalVisible(true);
      }
    } catch (error) {
      console.error('获取劳动者详情失败:', error);
      message.error('获取劳动者详情失败');
    }
  };

  const formatSalary = (job) => {
    const { salary, salaryType } = job;
    const unit = getSalaryTypeText(salaryType);
    if (salary) {
      return `${salary}元/${unit}`;
    }
    return '面议';
  };

  const columns = [
    {
      title: '岗位信息',
      key: 'jobInfo',
      render: (_, record) => (
        <div>
          <div style={{ fontWeight: 'bold', marginBottom: 4 }}>{record.title}</div>
          <div style={{ color: '#666', fontSize: '12px' }}>
            <BankOutlined style={{ marginRight: 4 }} />
            店主：{record.employer?.user?.realName || record.employer?.user?.username || '未设置'}
          </div>
          <div style={{ color: '#999', fontSize: '11px' }}>
            电话：{record.employer?.user?.phone || '未设置'}
          </div>
        </div>
      )
    },
    {
      title: '岗位类型',
      dataIndex: 'jobType',
      key: 'jobType',
      render: (type) => (
        <Tag color="blue">
          {getJobTypeText(type)}
        </Tag>
      )
    },
    {
      title: '薪资',
      key: 'salary',
      render: (_, record) => (
        <div style={{ fontWeight: 'bold', color: '#f50' }}>
          {formatSalary(record)}
        </div>
      )
    },
    {
      title: '工作地点',
      dataIndex: 'workLocation',
      key: 'workLocation',
      ellipsis: true
    },
    {
      title: '分配劳动者',
      key: 'assignedWorker',
      render: (_, record) => {
        if (record.status === 'WORKER_ASSIGNED' && record.assignedWorker) {
          return (
            <Button 
              type="link" 
              onClick={() => showWorkerDetail(record.assignedWorkerId)}
              style={{ padding: 0 }}
            >
              {record.assignedWorker.user.realName || record.assignedWorker.user.username}
              <br />
              <span style={{ fontSize: '12px', color: '#666' }}>
                {record.assignedWorker.user.phone}
              </span>
            </Button>
          );
        }
        return record.status === 'WAITING_FOR_WORKER' ? '等待分配' : '-';
      }
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <Tag color={getStatusColor(status)}>
          {getStatusText(status)}
        </Tag>
      )
    },
    {
      title: '发布时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (time) => time?.substring(0, 16) || '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 200,
      render: (_, record) => (
        <Space size="small">
          <Button 
            type="link" 
            icon={<EyeOutlined />}
            onClick={() => setSelectedJob(record) || setDetailModalVisible(true)}
          >
            详情
          </Button>
          {record.status === 'PENDING' && (
            <Button 
              type="link" 
              icon={<CheckOutlined />}
              style={{ color: 'green' }}
              onClick={() => showAuditModal(record)}
            >
              审核
            </Button>
          )}
          <Popconfirm
            title="确定要删除这个岗位吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="link" 
              danger
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
          <Space>
            <Select
              placeholder="选择状态"
              style={{ width: 120 }}
              allowClear
              value={filters.status}
              onChange={(value) => setFilters(prev => ({ ...prev, status: value || '' }))}
            >
              <Option value="PENDING">待审核</Option>
              <Option value="PUBLISHED">已发布</Option>
              <Option value="MATCHED">已匹配</Option>
              <Option value="COMPLETED">已完成</Option>
              <Option value="CANCELLED">已取消</Option>
              <Option value="REJECTED">已拒绝</Option>
            </Select>
            <Select
              placeholder="选择岗位类型"
              style={{ width: 120 }}
              allowClear
              value={filters.jobType}
              onChange={(value) => setFilters(prev => ({ ...prev, jobType: value || '' }))}
            >
              <Option value="FULL_TIME">全职</Option>
              <Option value="PART_TIME">兼职</Option>
              <Option value="TEMPORARY">临时工</Option>
              <Option value="INTERNSHIP">实习</Option>
            </Select>
          </Space>
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={() => setAddModalVisible(true)}
          >
            新增岗位
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={jobs}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize }));
            }
          }}
        />
      </Card>

      {/* 岗位详情弹窗 */}
      <Modal
        title="岗位详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={null}
        width={800}
      >
        {selectedJob && (
          <Descriptions column={2} bordered>
            <Descriptions.Item label="岗位ID">{selectedJob.id}</Descriptions.Item>
            <Descriptions.Item label="雇主">{selectedJob.employerName}</Descriptions.Item>
            <Descriptions.Item label="岗位标题">{selectedJob.jobTitle}</Descriptions.Item>
            <Descriptions.Item label="岗位类型">
              <Tag color="blue">{getJobTypeText(selectedJob.jobType)}</Tag>
            </Descriptions.Item>
            <Descriptions.Item label="薪资范围">{formatSalary(selectedJob)}</Descriptions.Item>
            <Descriptions.Item label="工作地点">{selectedJob.workLocation}</Descriptions.Item>
            <Descriptions.Item label="需要人数">{selectedJob.requiredWorkers}人</Descriptions.Item>
            <Descriptions.Item label="已匹配人数">{selectedJob.matchedWorkers}人</Descriptions.Item>
            <Descriptions.Item label="状态">
              <Tag color={getStatusColor(selectedJob.status)}>
                {getStatusText(selectedJob.status)}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="发布时间">{selectedJob.createdAt}</Descriptions.Item>
            <Descriptions.Item label="过期时间">{selectedJob.expireAt}</Descriptions.Item>
            <Descriptions.Item label="工作时间">{selectedJob.workTime || '面议'}</Descriptions.Item>
            <Descriptions.Item label="岗位描述" span={2}>
              {selectedJob.jobDescription}
            </Descriptions.Item>
            <Descriptions.Item label="技能要求" span={2}>
              {selectedJob.skillRequirements || '无特殊要求'}
            </Descriptions.Item>
          </Descriptions>
        )}
      </Modal>

      {/* 审核弹窗 */}
      <Modal
        title="岗位审核"
        open={auditModalVisible}
        onCancel={() => setAuditModalVisible(false)}
        onOk={() => form.submit()}
        okText="提交审核"
        cancelText="取消"
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleAudit}
        >
          <Form.Item
            label="审核结果"
            name="status"
            rules={[{ required: true, message: '请选择审核结果' }]}
          >
            <Select>
              <Option value="PUBLISHED">
                <CheckOutlined style={{ color: 'green', marginRight: 8 }} />
                通过并发布
              </Option>
              <Option value="REJECTED">
                <CloseOutlined style={{ color: 'red', marginRight: 8 }} />
                拒绝
              </Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="审核备注"
            name="auditRemark"
            rules={[{ required: true, message: '请输入审核备注' }]}
          >
            <TextArea 
              rows={4} 
              placeholder="请输入审核意见或拒绝原因"
            />
          </Form.Item>
        </Form>
      </Modal>

      {/* 新增岗位弹窗 */}
      <Modal
        title="新增岗位"
        open={addModalVisible}
        onCancel={() => {
          setAddModalVisible(false);
          addForm.resetFields();
        }}
        onOk={() => addForm.submit()}
        width={800}
        okText="创建岗位"
        cancelText="取消"
      >
        <Form
          form={addForm}
          layout="vertical"
          onFinish={handleAddJob}
        >
          <Form.Item
            label="选择用工方"
            name="employerId"
            rules={[{ required: true, message: '请选择用工方' }]}
          >
            <Select 
              placeholder="请选择用工方"
              showSearch
              filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {employers.map(employer => (
                <Option key={employer.id} value={employer.id}>
                  {employer.companyName || employer.user?.realName || employer.user?.username} 
                  ({employer.user?.phone})
                </Option>
              ))}
            </Select>
          </Form.Item>
          <Form.Item
            label="岗位标题"
            name="title"
            rules={[{ required: true, message: '请输入岗位标题' }]}
          >
            <Input placeholder="请输入岗位标题" />
          </Form.Item>
          <Form.Item
            label="岗位描述"
            name="description"
            rules={[{ required: true, message: '请输入岗位描述' }]}
          >
            <TextArea rows={4} placeholder="请输入岗位描述" />
          </Form.Item>
          <Form.Item
            label="岗位类型"
            name="jobType"
            rules={[{ required: true, message: '请选择岗位类型' }]}
          >
            <Select placeholder="请选择岗位类型">
              <Option value="FULL_TIME">全职</Option>
              <Option value="PART_TIME">兼职</Option>
              <Option value="TEMPORARY">临时工</Option>
              <Option value="INTERNSHIP">实习</Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="工作地点"
            name="location"
            rules={[{ required: true, message: '请输入工作地点' }]}
          >
            <Input placeholder="请输入工作地点" />
          </Form.Item>
          <Form.Item
            label="薪资"
            name="salary"
            rules={[{ required: true, message: '请输入薪资' }]}
          >
            <InputNumber 
              style={{ width: '100%' }}
              placeholder="请输入薪资"
              min={0}
              precision={2}
            />
          </Form.Item>
          <Form.Item
            label="薪资类型"
            name="salaryType"
            rules={[{ required: true, message: '请选择薪资类型' }]}
          >
            <Select placeholder="请选择薪资类型">
              <Option value="HOURLY">时薪</Option>
              <Option value="DAILY">日薪</Option>
              <Option value="MONTHLY">月薪</Option>
            </Select>
          </Form.Item>
          <Form.Item
            label="需要人数"
            name="requiredWorkers"
            rules={[{ required: true, message: '请输入需要人数' }]}
          >
            <InputNumber 
              style={{ width: '100%' }}
              placeholder="请输入需要人数"
              min={1}
            />
          </Form.Item>
          <Form.Item
            label="工作时间"
          >
            <Input.Group compact>
              <Form.Item
                name="workStartTime"
                style={{ display: 'inline-block', width: 'calc(50% - 12px)' }}
              >
                <DatePicker 
                  showTime 
                  placeholder="开始时间"
                  style={{ width: '100%' }}
                />
              </Form.Item>
              <Form.Item
                name="workEndTime"
                style={{ display: 'inline-block', width: 'calc(50% - 12px)', marginLeft: '24px' }}
              >
                <DatePicker 
                  showTime 
                  placeholder="结束时间"
                  style={{ width: '100%' }}
                />
              </Form.Item>
            </Input.Group>
          </Form.Item>
          <Form.Item
            label="岗位要求"
            name="requirements"
          >
            <TextArea rows={3} placeholder="请输入岗位要求（可选）" />
          </Form.Item>
          <Form.Item
            label="福利待遇"
            name="benefits"
          >
            <TextArea rows={3} placeholder="请输入福利待遇（可选）" />
          </Form.Item>
          <Form.Item
            label="联系人"
            name="contactPerson"
          >
            <Input placeholder="请输入联系人（可选）" />
          </Form.Item>
          <Form.Item
            label="联系电话"
            name="contactPhone"
          >
            <Input placeholder="请输入联系电话（可选）" />
          </Form.Item>
          <Form.Item
            label="分配劳动者"
            name="assignedWorkerId"
            help="可选，如果选择劳动者，岗位状态将设为已获取用工"
          >
            <Select 
              placeholder="请选择劳动者（可选）"
              allowClear
              showSearch
              filterOption={(input, option) =>
                option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {workers.map(worker => (
                <Option key={worker.id} value={worker.id}>
                  {worker.user?.realName || worker.user?.username} 
                  ({worker.user?.phone})
                </Option>
              ))}
            </Select>
          </Form.Item>
        </Form>
      </Modal>

      {/* 岗位详情模态框 */}
      <Modal
        title="岗位详情"
        open={detailModalVisible}
        onCancel={() => setDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {selectedJob && (
          <div>
            {/* 店主信息部分 */}
            <Card title="店主信息" style={{ marginBottom: 16 }}>
              <Descriptions bordered column={2}>
                <Descriptions.Item label="店主姓名" span={1}>
                  {selectedJob.employer?.user?.realName || selectedJob.employer?.user?.username || '未设置'}
                </Descriptions.Item>
                <Descriptions.Item label="联系电话" span={1}>
                  {selectedJob.employer?.user?.phone || '未设置'}
                </Descriptions.Item>
                <Descriptions.Item label="身份证号" span={1}>
                  {selectedJob.employer?.user?.idCard || '未设置'}
                </Descriptions.Item>
                <Descriptions.Item label="地址" span={1}>
                  {selectedJob.employer?.user?.address || '未设置'}
                </Descriptions.Item>
                <Descriptions.Item label="公司名称" span={2}>
                  {selectedJob.employer?.companyName || '未设置'}
                </Descriptions.Item>
                <Descriptions.Item label="营业地址" span={2}>
                  {selectedJob.employer?.businessAddress || '未设置'}
                </Descriptions.Item>
                <Descriptions.Item label="法人代表" span={1}>
                  {selectedJob.employer?.legalPerson || '未设置'}
                </Descriptions.Item>
                <Descriptions.Item label="联系电话" span={1}>
                  {selectedJob.employer?.contactPhone || '未设置'}
                </Descriptions.Item>
              </Descriptions>
            </Card>

            {/* 岗位详细信息部分 */}
            <Card title="岗位详细信息">
              <Descriptions bordered column={2}>
                <Descriptions.Item label="岗位标题" span={2}>
                  {selectedJob.title}
                </Descriptions.Item>
                <Descriptions.Item label="岗位类型" span={1}>
                  <Tag color="blue">{getJobTypeText(selectedJob.jobType)}</Tag>
                </Descriptions.Item>
                <Descriptions.Item label="薪资待遇" span={1}>
                  <span style={{ fontWeight: 'bold', color: '#f50' }}>
                    {formatSalary(selectedJob)}
                  </span>
                </Descriptions.Item>
                <Descriptions.Item label="工作地点" span={2}>
                  {selectedJob.location}
                </Descriptions.Item>
                <Descriptions.Item label="招聘人数" span={1}>
                  {selectedJob.requiredCount}人
                </Descriptions.Item>
                <Descriptions.Item label="工作时间" span={1}>
                  {selectedJob.startTime && selectedJob.endTime ? 
                    `${new Date(selectedJob.startTime).toLocaleString()} - ${new Date(selectedJob.endTime).toLocaleString()}` : 
                    '未设置'
                  }
                </Descriptions.Item>
                <Descriptions.Item label="岗位描述" span={2}>
                  {selectedJob.description || '暂无描述'}
                </Descriptions.Item>
                <Descriptions.Item label="技能要求" span={2}>
                  {selectedJob.skillRequirements || '暂无要求'}
                </Descriptions.Item>
                <Descriptions.Item label="其他要求" span={2}>
                  {selectedJob.otherRequirements || '暂无其他要求'}
                </Descriptions.Item>
                <Descriptions.Item label="联系信息" span={2}>
                  {selectedJob.contactInfo || '暂无联系信息'}
                </Descriptions.Item>
                <Descriptions.Item label="状态" span={1}>
                  <Tag color={getStatusColor(selectedJob.status)}>
                    {getStatusText(selectedJob.status)}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="发布时间" span={1}>
                  {selectedJob.createdAt ? new Date(selectedJob.createdAt).toLocaleString() : '-'}
                </Descriptions.Item>
                {selectedJob.auditRemark && (
                  <Descriptions.Item label="审核备注" span={2}>
                    {selectedJob.auditRemark}
                  </Descriptions.Item>
                )}
              </Descriptions>
            </Card>
          </div>
        )}
      </Modal>

      {/* 劳动者详情弹框 */}
      <Modal
        title="劳动者详细信息"
        visible={workerDetailModalVisible}
        onCancel={() => setWorkerDetailModalVisible(false)}
        footer={[
          <Button key="close" onClick={() => setWorkerDetailModalVisible(false)}>
            关闭
          </Button>
        ]}
        width={800}
      >
        {selectedWorker && (
          <div>
            <Card title="基本信息" style={{ marginBottom: 16 }}>
              <Descriptions bordered column={2}>
                <Descriptions.Item label="姓名" span={1}>
                  {selectedWorker.user.realName || selectedWorker.user.username}
                </Descriptions.Item>
                <Descriptions.Item label="联系电话" span={1}>
                  {selectedWorker.user.phone}
                </Descriptions.Item>
                <Descriptions.Item label="身份证号" span={1}>
                  {selectedWorker.user.idCard || '未设置'}
                </Descriptions.Item>
                <Descriptions.Item label="地址" span={1}>
                  {selectedWorker.user.address || '未设置'}
                </Descriptions.Item>
                <Descriptions.Item label="用户状态" span={1}>
                  <Tag color={selectedWorker.user.status === 'ACTIVE' ? 'green' : 'red'}>
                    {selectedWorker.user.status === 'ACTIVE' ? '正常' : '禁用'}
                  </Tag>
                </Descriptions.Item>
                <Descriptions.Item label="注册时间" span={1}>
                  {selectedWorker.user.createdAt ? new Date(selectedWorker.user.createdAt).toLocaleString() : '未知'}
                </Descriptions.Item>
              </Descriptions>
            </Card>

            <Card title="工作信息">
              <Descriptions bordered column={2}>
                <Descriptions.Item label="技能特长" span={2}>
                  {selectedWorker.skills || '未填写'}
                </Descriptions.Item>
                <Descriptions.Item label="工作经验" span={2}>
                  {selectedWorker.workExperience || '未填写'}
                </Descriptions.Item>
                <Descriptions.Item label="期望薪资" span={1}>
                  {selectedWorker.expectedSalary ? `${selectedWorker.expectedSalary}元` : '未设置'}
                </Descriptions.Item>
                <Descriptions.Item label="工作半径" span={1}>
                  {selectedWorker.workRadius ? `${selectedWorker.workRadius}公里` : '未设置'}
                </Descriptions.Item>
                <Descriptions.Item label="可工作时间" span={2}>
                  {selectedWorker.availableTime || '未设置'}
                </Descriptions.Item>
                <Descriptions.Item label="资格证书" span={2}>
                  {selectedWorker.certificates || '无'}
                </Descriptions.Item>
                <Descriptions.Item label="完成工作数" span={1}>
                  {selectedWorker.completedJobs || 0}个
                </Descriptions.Item>
                <Descriptions.Item label="评分" span={1}>
                  {selectedWorker.rating ? `${selectedWorker.rating}分` : '暂无评分'}
                </Descriptions.Item>
              </Descriptions>
            </Card>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default JobManagement;
